package com.lc.builder;

import com.lc.bean.Constants;
import com.lc.bean.FieldInfo;
import com.lc.bean.TableInfo;
import com.lc.utils.DateUtils;
import com.lc.utils.StringUtils;
import org.apache.commons.lang3.ArrayUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.*;
import java.nio.file.Files;
import java.util.List;
import java.util.Map;

/**
 * 功能：
 * 作者：lc
 * 日期：2024/8/5 23:56
 */
public class BuildService {
    private static final Logger logger = LoggerFactory.getLogger(BuildService.class);

    public static void execute(TableInfo tableInfo) {
        String pathName = tableInfo.getBeanName() + "Service";
        File folder = new File(Constants.PATH_SERVICE);
        if (!folder.exists()) {
            folder.mkdirs();
        }
        File poFile = new File(folder, pathName + ".java");
        OutputStream out = null;
        OutputStreamWriter outw = null;
        BufferedWriter bw = null;
        try {
            out = Files.newOutputStream(poFile.toPath());
            outw = new OutputStreamWriter(out, "utf8");
            bw = new BufferedWriter(outw);
            bw.write("package " + Constants.PACKAGE_SERVICE + ";\n");
            bw.newLine();
            bw.write("import " + Constants.PACKAGE_PO + "." + tableInfo.getBeanName() + ";\n");
            bw.write("import " + Constants.PACKAGE_QUERY + "." + tableInfo.getBeanParamName() + ";\n");
            bw.write("import " + Constants.PACKAGE_VO  + "." +"PaginationResultVO;");
            bw.newLine();
            bw.write("import java.util.List;\n");
            BuildQuery.havaBeanField(tableInfo, bw);
            if (tableInfo.getHaveDate() || tableInfo.getHaveDateTime()) {
                bw.write("import java.util.Date;\n" +
                        Constants.BEAN_DATE_FORMAT_CLASS +
                        "\n" +
                        "import com.lc.enums.DateTimePatterEnum;\n" +
                        "import com.lc.utils.DateUtils;\n" +
                        Constants.BEAN_DATE_UNFORMAT_CLASS +
                        "\n");
            }
            bw.write("public interface " + pathName + "{\n");
            BuildComment.createFieldComment(bw, "根据条件查询列表");
            bw.write("\tList<" + tableInfo.getBeanName() + "> selectAllByParam(" + tableInfo.getBeanParamName() + " param);");
            BuildComment.createFieldComment(bw, "根据条件查询数量");
            bw.write("\tInteger selectCountByParam(" + tableInfo.getBeanParamName() + " param);");
            BuildComment.createFieldComment(bw, "分页查询");
            bw.write("\tPaginationResultVO<" + tableInfo.getBeanName() + "> selectAllBtPage(" + tableInfo.getBeanParamName() + " param);");
            BuildComment.createFieldComment(bw, "新增");
            bw.write("\tInteger add(" + tableInfo.getBeanParamName() + " bean);");
            BuildComment.createFieldComment(bw, "新增或者更新");
            bw.write("\tInteger addOrUpdate(" + tableInfo.getBeanParamName() + " bean);");
            BuildComment.createFieldComment(bw, "批量新增");
            bw.write("\tInteger addBatch(List<" + tableInfo.getBeanParamName() + "> listBean);");
            BuildComment.createFieldComment(bw, "批量新增/修改");
            bw.write("\tInteger addOrUpdateBatch(List<" + tableInfo.getBeanParamName() + "> listBean);");
            Map<String, List<FieldInfo>> keyIndexMap = tableInfo.getKeyIndexMap();
            for (Map.Entry<String, List<FieldInfo>> entry :
                    keyIndexMap.entrySet()) {
                List<FieldInfo> keyFieldInfoList= entry.getValue();
                int index=0;
                StringBuffer methodName = new StringBuffer();
                StringBuffer methodParam = new StringBuffer();
                StringBuffer  methodBatch= new StringBuffer();
                for (FieldInfo fieldInfo :
                        keyFieldInfoList) {
                    index++;
                    methodName.append(StringUtils.upperCaseFirstLetter(fieldInfo.getPropertyName()));
                    methodParam.append(fieldInfo.getJavaType()).append(" ").append(fieldInfo.getPropertyName());
                    methodBatch.append(fieldInfo.getJavaType()).append("[] ").append(fieldInfo.getPropertyName()).append("s");
                    if (index< keyFieldInfoList.size()){
                        methodName.append("And");
                    }
                    if (index< keyFieldInfoList.size()){
                        methodParam.append(", ");
                    }

                }
                BuildComment.createFieldComment(bw,"根据"+methodName+"查询");
                bw.write("\t"+tableInfo.getBeanName()+" getBy"+methodName+"("+methodParam+");\n");

                BuildComment.createFieldComment(bw,"根据"+methodName+"更新");
                bw.write("\tInteger updateBy" +methodName+"("+tableInfo.getBeanName()+" bean, "+methodParam+");\n");

                BuildComment.createFieldComment(bw,"根据"+methodName+"删除");
                bw.write("\tInteger deleteBy"+methodName+"( "+methodParam+");\n");

                BuildComment.createFieldComment(bw,"根据"+methodName+"批量删除");
                bw.write("\tInteger deleteBy"+methodName+"s( "+methodBatch+");\n");

            }

            bw.write("\n}");

            bw.flush();
        } catch (Exception e) {
            logger.error("创建Service层失败~", e);
        } finally {
            if (bw != null) {
                try {
                    bw.close();
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            }
            if (outw != null) {
                try {
                    outw.close();
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            }
            if (out != null) {
                try {
                    out.close();
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            }
        }

    }
}
